package com.ruoyi.framework.extendsions.config;

import com.ruoyi.framework.extendsions.security.filter.SmsCodeAuthenticationFilter;
import com.ruoyi.framework.extendsions.security.provoder.SmsCodeAuthenticationProvider;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Arrays;
import java.util.List;


@Configuration
@Order(1)
public class SmsSecurityConfig {

    @Autowired
    private UserDetailsService userPhoneCodeDetailsService; // 注入你的手机号 UserDetailsService

    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    // 路径根据你项目实际调整
    private static final String SMS_LOGIN_PATH = "/app/reg-and-login";

    @Bean
    public SecurityFilterChain smsSecurityFilterChain(HttpSecurity http) throws Exception {

        // 1) 本地 new 出 Provider（**不是** @Bean）
        SmsCodeAuthenticationProvider smsProvider = new SmsCodeAuthenticationProvider(userPhoneCodeDetailsService);

        // 2) 本地 new 出 ProviderManager（**不是** @Bean，避免与全局 AuthenticationManager 冲突）
//        List<SmsCodeAuthenticationProvider> providers = Arrays.asList(smsProvider);
        ProviderManager localAuthManager = new ProviderManager(smsProvider);

        // 3) 创建 Filter，传入 localAuthManager
        SmsCodeAuthenticationFilter smsFilter = new SmsCodeAuthenticationFilter(SMS_LOGIN_PATH, localAuthManager);
        // 你可以按需设置 success/failure handler:
        // smsFilter.setAuthenticationSuccessHandler(...);
        // smsFilter.setAuthenticationFailureHandler(...);

        // 4) 构建仅处理该路径的 SecurityFilterChain
        http
                // 这里使用 requestMatchers 限定匹配的路径（只为该路径构建链）
                .requestMatchers(matchers -> matchers.antMatchers(SMS_LOGIN_PATH))
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                // 把自定义 Filter 放在 UsernamePasswordAuthenticationFilter 之前
                .addFilterBefore(smsFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean(name = "smsAuthenticationManager")
    public AuthenticationManager smsAuthenticationManager(UserDetailsService userPhoneCodeDetailsService) {
        SmsCodeAuthenticationProvider smsProvider = new SmsCodeAuthenticationProvider(userPhoneCodeDetailsService);
        return new ProviderManager(Arrays.asList(smsProvider));
    }
}